package com.eight.cloud.core.utils.supply;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.ttl.TransmittableThreadLocal;
import com.eight.cloud.core.global.exception.CustomException;
import com.eight.cloud.core.global.model.BaseUser;
import com.eight.cloud.core.utils.quick.GenericTypeChangeUtil;

import static com.eight.cloud.core.global.result.ResultCode.USER_NOT_LOGIN;

/**
 * 用户信息上下文
 *
 * @ClassName: UserContext
 * @Author: TXC
 * @Date: 2024-10-08 22:57
 **/
public class UserContext {
    private static final TransmittableThreadLocal<BaseUser> USER_CONTEXT = new TransmittableThreadLocal<>();

    /**
     * 保存用户信息
     *
     * @param user 用户信息
     */
    public static <T extends BaseUser> void setUser(T user) {
        USER_CONTEXT.set(user);
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    public static <T extends BaseUser> T getUser() {
        if (ObjectUtil.isNotNull(USER_CONTEXT.get())) {
            return GenericTypeChangeUtil.typeConversion(USER_CONTEXT.get(), USER_CONTEXT.get().getClass());
        }
        throw new CustomException(USER_NOT_LOGIN);
    }


    /**
     * 清空用户信息
     */
    public static void clear() {
        USER_CONTEXT.remove();
    }
}
